#include <iostream>
#include <sstream>
#include <string>
#include <unistd.h>
#include "TcpServer.hpp"
#include "Protocol.hpp"
using namespace std;

void ArithmeticServer(int sockfd)
{
    // cout << "ArithmeticServer" << endl;
    while (true)
    {
        char buffer[128];
        ssize_t n = recv(sockfd, (void *)buffer, sizeof(buffer), 0);
        Request rq(buffer);

        stringstream result;
        result << rq.Result().GetResult() << " " << rq.Result().GetCode();
        // cout << rq.Result().GetResult() << " " << rq.Result().GetCode() << endl;

        send(sockfd, (void *)result.str().c_str(), result.str().size(), 0);

    }

    // while (true)
    // {
    //     Request rq;
    //     ssize_t n = recv(sockfd, (void *)&rq, sizeof(rq), 0);
    //     if(n == 0)
    //         return;
    //     Response rp = rq.Result();
    //     send(sockfd, (void *)&rp, sizeof(rp), 0);
    // }

    cout << "Client quit" << endl;
}

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        cout << "Incorrect use: " << endl
             << "    " << argv[0] << " port" << endl;
        return 1;
    }

    uint16_t port = stoi(argv[1]);

    unique_ptr<TcpServer> up(new TcpServer(port, ArithmeticServer));

    up->Loop();
    return 0;
}